import * as fs from 'fs';
import { FrontendParser } from '../utils/FrontendParser';

/**
 * CSS/SCSS重构工具
 */
export class CSSRefactor {
    
    /**
     * 转换CSS为BEM命名规范
     */
    async convertToBEM(filePath: string): Promise<{
        success: boolean;
        message: string;
        filesModified: string[];
        convertedClasses: Array<{
            original: string;
            bem: string;
            line: number;
        }>;
        appliedChanges: string[];
        errors: string[];
    }> {
        const result = {
            success: false,
            message: '',
            filesModified: [] as string[] as string[],
            convertedClasses: [] as Array<{
                original: string;
                bem: string;
                line: number;
            }>,
            appliedChanges: [] as string[] as string[],
            errors: [] as string[] as string[]
        };

        try {
            const content = await fs.promises.readFile(filePath, 'utf-8');
            const fileType = this.detectFileType(filePath);
            
            // 分析当前CSS结构
            const classAnalysis = this.analyzeCSSClasses(content);
            
            if (classAnalysis.length === 0) {
                result.message = '未找到可以转换为BEM格式的CSS类';
                return result;
            }

            // 执行BEM转换
            const bemConversion = await this.performBEMConversion(content, classAnalysis);
            
            // 备份原文件
            const backupPath = filePath.replace(/\.(css|scss)$/, '.pre-bem-backup.$1');
            await fs.promises.writeFile(backupPath, content);

            // 写入转换后的内容
            await fs.promises.writeFile(filePath, bemConversion.content);

            result.success = true;
            result.message = `成功转换${bemConversion.convertedClasses.length}个类为BEM格式`;
            result.filesModified = [filePath];
            result.convertedClasses = bemConversion.convertedClasses;
            result.appliedChanges = bemConversion.convertedClasses.map(c => `${c.original} → ${c.bem}`);

        } catch (error) {
            result.errors.push(`BEM转换失败: ${error}`);
            result.message = `转换失败: ${error}`;
        }

        return result;
    }

    /**
     * 转换CSS为CSS-in-JS (styled-components格式)
     */
    async convertToCSSInJS(filePath: string): Promise<{
        success: boolean;
        message: string;
        filesModified: string[];
        styledComponents: Array<{
            name: string;
            styles: string;
            originalClass: string;
        }>;
        appliedChanges: string[];
        errors: string[];
    }> {
        const result = {
            success: false,
            message: '',
            filesModified: [] as string[],
            styledComponents: [] as Array<{
                name: string;
                styles: string;
                originalClass: string;
            }>,
            appliedChanges: [] as string[],
            errors: [] as string[]
        };

        try {
            const content = await fs.promises.readFile(filePath, 'utf-8');
            
            // 解析CSS规则
            const cssRules = this.parseCSSRules(content);
            
            if (cssRules.length === 0) {
                result.message = '未找到可以转换的CSS规则';
                return result;
            }

            // 转换为styled-components
            const styledComponents = this.convertToStyledComponents(cssRules);
            
            // 生成新的JS文件
            const jsFilePath = filePath.replace(/\.(css|scss)$/, '.styles.js');
            const styledComponentsContent = this.generateStyledComponentsFile(styledComponents);
            
            await fs.promises.writeFile(jsFilePath, styledComponentsContent);

            result.success = true;
            result.message = `成功转换${styledComponents.length}个组件为CSS-in-JS格式`;
            result.filesModified = [jsFilePath];
            result.styledComponents = styledComponents;
            result.appliedChanges = styledComponents.map(sc => `生成styled组件: ${sc.name}`);

        } catch (error) {
            result.errors.push(`CSS-in-JS转换失败: ${error}`);
            result.message = `转换失败: ${error}`;
        }

        return result;
    }

    /**
     * 优化SCSS代码结构
     */
    async optimizeSCSS(filePath: string): Promise<{
        success: boolean;
        message: string;
        filesModified: string[];
        optimizations: Array<{
            type: string;
            description: string;
            applied: boolean;
        }>;
        appliedChanges: string[];
        errors: string[];
    }> {
        const result = {
            success: false,
            message: '',
            filesModified: [] as string[],
            optimizations: [] as Array<{
                type: string;
                description: string;
                applied: boolean;
            }>,
            appliedChanges: [] as string[],
            errors: [] as string[]
        };

        try {
            const content = await fs.promises.readFile(filePath, 'utf-8');
            
            if (!filePath.endsWith('.scss')) {
                result.message = '只支持SCSS文件优化';
                return result;
            }

            let optimizedContent = content;
            const optimizations: Array<{
                type: string;
                description: string;
                applied: boolean;
            }> = [];

            // 1. 提取变量
            const variableExtraction = this.extractVariables(optimizedContent);
            if (variableExtraction.modified) {
                optimizedContent = variableExtraction.content;
                optimizations.push({
                    type: 'variables',
                    description: '提取重复值为SCSS变量',
                    applied: true
                });
                result.appliedChanges.push('提取SCSS变量');
            }

            // 2. 创建mixins
            const mixinCreation = this.createMixins(optimizedContent);
            if (mixinCreation.modified) {
                optimizedContent = mixinCreation.content;
                optimizations.push({
                    type: 'mixins',
                    description: '创建可复用的mixins',
                    applied: true
                });
                result.appliedChanges.push('创建SCSS mixins');
            }

            // 3. 优化嵌套结构
            const nestingOptimization = this.optimizeNesting(optimizedContent);
            if (nestingOptimization.modified) {
                optimizedContent = nestingOptimization.content;
                optimizations.push({
                    type: 'nesting',
                    description: '优化嵌套结构，避免过深嵌套',
                    applied: true
                });
                result.appliedChanges.push('优化嵌套结构');
            }

            // 4. 合并重复选择器
            const selectorMerging = this.mergeDuplicateSelectors(optimizedContent);
            if (selectorMerging.modified) {
                optimizedContent = selectorMerging.content;
                optimizations.push({
                    type: 'selector-merging',
                    description: '合并重复的选择器',
                    applied: true
                });
                result.appliedChanges.push('合并重复选择器');
            }

            if (optimizedContent !== content) {
                await fs.promises.writeFile(filePath, optimizedContent);
                result.filesModified = [filePath];
            }

            result.success = true;
            result.message = `应用了${result.appliedChanges.length}个SCSS优化`;
            result.optimizations = optimizations;

        } catch (error) {
            result.errors.push(`SCSS优化失败: ${error}`);
            result.message = `优化失败: ${error}`;
        }

        return result;
    }

    /**
     * CSS性能优化
     */
    async optimizeCSSPerformance(filePath: string): Promise<{
        success: boolean;
        message: string;
        filesModified: string[];
        optimizations: Array<{
            type: string;
            description: string;
            before: string;
            after: string;
            impact: 'high' | 'medium' | 'low';
        }>;
        appliedChanges: string[];
        errors: string[];
    }> {
        const result = {
            success: false,
            message: '',
            filesModified: [] as string[],
            optimizations: [] as Array<{
                type: string;
                description: string;
                before: string;
                after: string;
                impact: 'high' | 'medium' | 'low';
            }>,
            appliedChanges: [] as string[],
            errors: [] as string[]
        };

        try {
            const content = await fs.promises.readFile(filePath, 'utf-8');
            let optimizedContent = content;
            const optimizations: Array<{
                type: string;
                description: string;
                before: string;
                after: string;
                impact: 'high' | 'medium' | 'low';
            }> = [];

            // 1. 优化选择器性能
            const selectorOptimization = this.optimizeSelectors(optimizedContent);
            if (selectorOptimization.changes.length > 0) {
                optimizedContent = selectorOptimization.content;
                optimizations.push(...selectorOptimization.changes);
                result.appliedChanges.push('优化选择器性能');
            }

            // 2. 移除未使用的CSS
            const unusedCSSRemoval = this.removeUnusedCSS(optimizedContent);
            if (unusedCSSRemoval.modified) {
                optimizedContent = unusedCSSRemoval.content;
                optimizations.push({
                    type: 'unused-css',
                    description: '移除未使用的CSS规则',
                    before: '大量未使用规则',
                    after: '仅保留使用的规则',
                    impact: 'high'
                });
                result.appliedChanges.push('移除未使用CSS');
            }

            // 3. 优化CSS属性顺序
            const propertyOrdering = this.optimizePropertyOrder(optimizedContent);
            if (propertyOrdering.modified) {
                optimizedContent = propertyOrdering.content;
                optimizations.push({
                    type: 'property-order',
                    description: '按照渲染优先级排序CSS属性',
                    before: '随机属性顺序',
                    after: '优化的属性顺序',
                    impact: 'low'
                });
                result.appliedChanges.push('优化属性顺序');
            }

            // 4. 压缩和精简
            const minification = this.minifyCSS(optimizedContent);
            if (minification.modified) {
                optimizedContent = minification.content;
                optimizations.push({
                    type: 'minification',
                    description: '移除多余空白和注释',
                    before: `${content.length} 字符`,
                    after: `${optimizedContent.length} 字符`,
                    impact: 'medium'
                });
                result.appliedChanges.push('压缩CSS');
            }

            if (optimizedContent !== content) {
                await fs.promises.writeFile(filePath, optimizedContent);
                result.filesModified = [filePath];
            }

            result.success = true;
            result.message = `应用了${result.appliedChanges.length}个性能优化`;
            result.optimizations = optimizations;

        } catch (error) {
            result.errors.push(`CSS性能优化失败: ${error}`);
            result.message = `优化失败: ${error}`;
        }

        return result;
    }

    private detectFileType(filePath: string): 'css' | 'scss' | 'less' {
        if (filePath.endsWith('.scss')) return 'scss';
        if (filePath.endsWith('.less')) return 'less';
        return 'css';
    }

    private analyzeCSSClasses(content: string): Array<{
        className: string;
        line: number;
        canBeBEM: boolean;
        suggestedBEM: string;
    }> {
        const classes: Array<{
            className: string;
            line: number;
            canBeBEM: boolean;
            suggestedBEM: string;
        }> = [];
        
        const lines = content.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 匹配CSS类选择器
            const classMatch = line.match(/^\.([a-zA-Z0-9_-]+)/);
            if (classMatch) {
                const className = classMatch[1];
                const canBeBEM = this.canConvertToBEM(className, content);
                const suggestedBEM = this.generateBEMName(className, content);
                
                classes.push({
                    className,
                    line: i + 1,
                    canBeBEM,
                    suggestedBEM
                });
            }
        }
        
        return classes;
    }

    private canConvertToBEM(className: string, content: string): boolean {
        // 检查是否已经是BEM格式
        if (className.includes('__') || className.includes('--')) {
            return false;
        }
        
        // 检查是否有相关的子元素或修饰符
        const relatedClasses = content.match(new RegExp(`\\.(${className}[a-zA-Z0-9_-]*)`, 'g'));
        return Boolean(relatedClasses && relatedClasses.length > 1);
    }

    private generateBEMName(className: string, content: string): string {
        // 简化BEM命名生成逻辑
        const relatedClasses = content.match(new RegExp(`\\.(${className}[a-zA-Z0-9_-]*)`, 'g'));
        
        if (relatedClasses && relatedClasses.length > 1) {
            // 假设第一个是block，其他是element
            return `${className}__element`;
        }
        
        return className;
    }

    private async performBEMConversion(
        content: string, 
        classAnalysis: Array<{className: string; line: number; canBeBEM: boolean; suggestedBEM: string}>
    ): Promise<{
        content: string;
        convertedClasses: Array<{original: string; bem: string; line: number}>;
    }> {
        let convertedContent = content;
        const convertedClasses: Array<{original: string; bem: string; line: number}> = [];
        
        for (const classInfo of classAnalysis) {
            if (classInfo.canBeBEM) {
                // 执行BEM转换
                const originalSelector = `.${classInfo.className}`;
                const bemSelector = `.${classInfo.suggestedBEM}`;
                
                convertedContent = convertedContent.replace(
                    new RegExp(`\\${originalSelector}(?![a-zA-Z0-9_-])`, 'g'),
                    bemSelector
                );
                
                convertedClasses.push({
                    original: classInfo.className,
                    bem: classInfo.suggestedBEM,
                    line: classInfo.line
                });
            }
        }
        
        return {
            content: convertedContent,
            convertedClasses
        };
    }

    private parseCSSRules(content: string): Array<{
        selector: string;
        rules: string;
        line: number;
    }> {
        const cssRules: Array<{
            selector: string;
            rules: string;
            line: number;
        }> = [];
        
        // 简化的CSS解析
        const rulePattern = /([^{]+)\s*\{([^}]+)\}/g;
        let match;
        
        while ((match = rulePattern.exec(content)) !== null) {
            const selector = match[1].trim();
            const rules = match[2].trim();
            const line = content.substring(0, match.index).split('\n').length;
            
            cssRules.push({
                selector,
                rules,
                line
            });
        }
        
        return cssRules;
    }

    private convertToStyledComponents(cssRules: Array<{selector: string; rules: string; line: number}>): Array<{
        name: string;
        styles: string;
        originalClass: string;
    }> {
        const styledComponents: Array<{
            name: string;
            styles: string;
            originalClass: string;
        }> = [];
        
        for (const rule of cssRules) {
            if (rule.selector.startsWith('.')) {
                const className = rule.selector.substring(1);
                const componentName = this.classNameToComponentName(className);
                
                styledComponents.push({
                    name: componentName,
                    styles: rule.rules,
                    originalClass: className
                });
            }
        }
        
        return styledComponents;
    }

    private classNameToComponentName(className: string): string {
        // 转换CSS类名为组件名
        return className
            .split(/[-_]/)
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join('');
    }

    private generateStyledComponentsFile(styledComponents: Array<{name: string; styles: string; originalClass: string}>): string {
        let content = `import styled from 'styled-components';\n\n`;
        
        for (const component of styledComponents) {
            content += `export const ${component.name} = styled.div\`\n`;
            content += `  ${component.styles.replace(/;/g, ';\n  ')}\n`;
            content += `\`;\n\n`;
        }
        
        return content;
    }

    private extractVariables(content: string): {modified: boolean; content: string} {
        let modified = false;
        let optimized = content;
        
        // 查找重复的颜色值
        const colorValues: Record<string, number> = {};
        const colorPattern = /#[0-9a-fA-F]{3,6}|rgb\([^)]+\)|rgba\([^)]+\)/g;
        let match;
        
        while ((match = colorPattern.exec(content)) !== null) {
            const color = match[0];
            colorValues[color] = (colorValues[color] || 0) + 1;
        }
        
        // 提取出现次数 >= 3 的颜色为变量
        const variablesToCreate: Array<{value: string; name: string}> = [];
        let variableIndex = 1;
        
        for (const [color, count] of Object.entries(colorValues)) {
            if (count >= 3) {
                variablesToCreate.push({
                    value: color,
                    name: `$color-${variableIndex++}`
                });
            }
        }
        
        if (variablesToCreate.length > 0) {
            // 在文件顶部添加变量声明
            const variableDeclarations = variablesToCreate
                .map(v => `${v.name}: ${v.value};`)
                .join('\n');
            
            optimized = `// SCSS Variables\n${variableDeclarations}\n\n${optimized}`;
            
            // 替换重复的颜色值
            for (const variable of variablesToCreate) {
                optimized = optimized.replace(
                    new RegExp(variable.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'),
                    variable.name
                );
            }
            
            modified = true;
        }
        
        return {modified, content: optimized};
    }

    private createMixins(content: string): {modified: boolean; content: string} {
        let modified = false;
        let optimized = content;
        
        // 检测重复的CSS模式，创建mixins
        const commonPatterns = [
            {
                name: 'flex-center',
                pattern: /display:\s*flex;\s*justify-content:\s*center;\s*align-items:\s*center;/g,
                mixin: '@mixin flex-center {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}'
            },
            {
                name: 'clearfix',
                pattern: /&::after\s*\{\s*content:\s*["']["'];\s*display:\s*table;\s*clear:\s*both;\s*\}/g,
                mixin: '@mixin clearfix {\n  &::after {\n    content: "";\n    display: table;\n    clear: both;\n  }\n}'
            }
        ];
        
        const mixinsToAdd: string[] = [];
        
        for (const pattern of commonPatterns) {
            const matches = content.match(pattern.pattern);
            if (matches && matches.length >= 2) {
                mixinsToAdd.push(pattern.mixin);
                optimized = optimized.replace(pattern.pattern, `@include ${pattern.name};`);
                modified = true;
            }
        }
        
        if (mixinsToAdd.length > 0) {
            const mixinDeclarations = mixinsToAdd.join('\n\n');
            optimized = `// SCSS Mixins\n${mixinDeclarations}\n\n${optimized}`;
        }
        
        return {modified, content: optimized};
    }

    private optimizeNesting(content: string): {modified: boolean; content: string} {
        // 检测过深的嵌套并建议优化
        let modified = false;
        let optimized = content;
        
        // 简化实现：警告超过3层嵌套
        const lines = content.split('\n');
        let nestingLevel = 0;
        const maxNesting = 3;
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            const openBraces = (line.match(/\{/g) || []).length;
            const closeBraces = (line.match(/\}/g) || []).length;
            
            nestingLevel += openBraces - closeBraces;
            
            if (nestingLevel > maxNesting) {
                // 添加注释警告
                lines[i] = `${line} // 警告: 嵌套过深 (${nestingLevel}层)，考虑拆分`;
                modified = true;
            }
        }
        
        if (modified) {
            optimized = lines.join('\n');
        }
        
        return {modified, content: optimized};
    }

    private mergeDuplicateSelectors(content: string): {modified: boolean; content: string} {
        // 简化实现：检测重复选择器
        let modified = false;
        let optimized = content;
        
        const selectorRules: Record<string, string[]> = {};
        const rulePattern = /([^{]+)\s*\{([^}]+)\}/g;
        let match;
        
        while ((match = rulePattern.exec(content)) !== null) {
            const selector = match[1].trim();
            const rules = match[2].trim();
            
            if (selectorRules[selector]) {
                selectorRules[selector].push(rules);
            } else {
                selectorRules[selector] = [rules];
            }
        }
        
        // 合并重复选择器的规则
        for (const [selector, rulesArray] of Object.entries(selectorRules)) {
            if (rulesArray.length > 1) {
                const mergedRules = rulesArray.join(';\n  ');
                const originalPattern = new RegExp(`${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\{[^}]+\\}`, 'g');
                const replacement = `${selector} {\n  ${mergedRules}\n}`;
                
                // 替换第一个匹配项，删除其他
                let isFirst = true;
                optimized = optimized.replace(originalPattern, (match) => {
                    if (isFirst) {
                        isFirst = false;
                        return replacement;
                    }
                    return '';
                });
                
                modified = true;
            }
        }
        
        return {modified, content: optimized};
    }

    private optimizeSelectors(content: string): {
        content: string;
        changes: Array<{
            type: string;
            description: string;
            before: string;
            after: string;
            impact: 'high' | 'medium' | 'low';
        }>;
    } {
        const changes: Array<{
            type: string;
            description: string;
            before: string;
            after: string;
            impact: 'high' | 'medium' | 'low';
        }> = [];
        
        let optimized = content;
        
        // 优化通用选择器
        const universalSelectorPattern = /\*\s*\{/g;
        if (universalSelectorPattern.test(content)) {
            changes.push({
                type: 'universal-selector',
                description: '避免使用通用选择器，影响性能',
                before: '* { }',
                after: '建议使用具体选择器',
                impact: 'high'
            });
        }
        
        // 优化后代选择器
        const descendantPattern = /(\w+\s+){3,}\w+\s*\{/g;
        const descendantMatches = content.match(descendantPattern);
        if (descendantMatches) {
            for (const match of descendantMatches) {
                changes.push({
                    type: 'descendant-selector',
                    description: '简化过长的后代选择器',
                    before: match.trim(),
                    after: '建议使用类选择器',
                    impact: 'medium'
                });
            }
        }
        
        return {content: optimized, changes};
    }

    private removeUnusedCSS(content: string): {modified: boolean; content: string} {
        // 简化实现：标记可能未使用的选择器
        let modified = false;
        let optimized = content;
        
        // 这里应该结合HTML/JS文件分析，简化实现只做注释标记
        const suspiciousSelectors = [
            /\.test-\w+/g,
            /\.debug-\w+/g,
            /\.old-\w+/g
        ];
        
        for (const pattern of suspiciousSelectors) {
            if (pattern.test(content)) {
                optimized = optimized.replace(pattern, (match) => `/* 可能未使用: ${match} */`);
                modified = true;
            }
        }
        
        return {modified, content: optimized};
    }

    private optimizePropertyOrder(content: string): {modified: boolean; content: string} {
        // CSS属性的推荐顺序
        const propertyOrder = [
            'position', 'top', 'right', 'bottom', 'left', 'z-index',
            'display', 'float', 'width', 'height', 'max-width', 'max-height', 'min-width', 'min-height',
            'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
            'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
            'margin-collapse', 'margin-top-collapse', 'margin-right-collapse', 'margin-bottom-collapse', 'margin-left-collapse',
            'overflow', 'overflow-x', 'overflow-y', 'clip', 'clear',
            'font', 'font-family', 'font-size', 'font-style', 'font-weight', 'font-variant', 'font-size-adjust',
            'font-stretch', 'font-effect', 'font-emphasize', 'font-emphasize-position', 'font-emphasize-style',
            'font-smooth', 'line-height', 'letter-spacing', 'word-spacing',
            'color', 'text-align', 'text-decoration', 'text-indent', 'text-justify', 'text-outline',
            'text-transform', 'text-wrap', 'text-overflow', 'text-overflow-ellipsis', 'text-overflow-mode',
            'text-shadow', 'white-space', 'word-wrap', 'word-break',
            'tab-size', 'hyphens', 'pointer-events', 'opacity', 'filter',
            'background', 'background-color', 'background-image', 'background-repeat', 'background-attachment',
            'background-position', 'background-position-x', 'background-position-y', 'background-clip',
            'background-origin', 'background-size',
            'border', 'border-width', 'border-style', 'border-color',
            'border-top', 'border-top-width', 'border-top-style', 'border-top-color',
            'border-right', 'border-right-width', 'border-right-style', 'border-right-color',
            'border-bottom', 'border-bottom-width', 'border-bottom-style', 'border-bottom-color',
            'border-left', 'border-left-width', 'border-left-style', 'border-left-color',
            'border-radius', 'border-top-left-radius', 'border-top-right-radius',
            'border-bottom-right-radius', 'border-bottom-left-radius',
            'border-image', 'border-image-source', 'border-image-slice', 'border-image-width',
            'border-image-outset', 'border-image-repeat', 'outline', 'outline-width', 'outline-style',
            'outline-color', 'outline-offset', 'box-shadow', 'visibility', 'cursor',
            'mix-blend-mode', 'isolation', 'backdrop-filter',
            'transform', 'transform-origin', 'transform-style', 'perspective', 'perspective-origin',
            'backface-visibility', 'transition', 'transition-delay', 'transition-timing-function',
            'transition-duration', 'transition-property', 'animation', 'animation-name',
            'animation-duration', 'animation-play-state', 'animation-timing-function', 'animation-delay',
            'animation-iteration-count', 'animation-direction'
        ];

        // 简化实现：仅在注释中建议属性顺序
        return {modified: false, content};
    }

    private minifyCSS(content: string): {modified: boolean; content: string} {
        let modified = false;
        let minified = content;
        
        // 移除多余的空白
        minified = minified.replace(/\s+/g, ' ');
        minified = minified.replace(/;\s*}/g, '}');
        minified = minified.replace(/{\s+/g, '{');
        minified = minified.replace(/}\s+/g, '}');
        minified = minified.replace(/,\s+/g, ',');
        minified = minified.replace(/:\s+/g, ':');
        
        // 移除注释
        minified = minified.replace(/\/\*.*?\*\//g, '');
        
        if (minified !== content) {
            modified = true;
        }
        
        return {modified, content: minified};
    }
}